import useLocale from '@/utils/useLocale';
import React, { useEffect, useMemo, useState } from 'react';
import moment from 'moment/moment';
import instance from '@/utils/request';
import { Card, Empty, Grid, Skeleton, Space, Statistic, Typography } from '@arco-design/web-react';
import { Chart, Legend, LineAdvance } from 'bizcharts';
import { UtilizationRecordResponse } from '@/constants/type';

const { Row, Col } = Grid;

const locale = {
  'en-US': {},
  'zh-CN': {
    'title.utilization.history': '历史稼动率',
    'title.utilization.realtime': '实时稼动率',
    'title.utilization': '稼动率',
    'label.last_refresh_datetime': '最后刷新时间：'
  }
};

const UtilizationPanel = (props: {
  id: number
}) => {
  const t = useLocale(locale);
  const [loadingHistory, setLoadingHistory] = useState<boolean>(false);
  const [loadingRealtime, setLoadingRealtime] = useState<boolean>(false);
  const [data, setData] = useState<UtilizationRecordResponse[]>([]);
  const [current, setCurrent] = useState<UtilizationRecordResponse>();
  const [lastRefreshDatetime, setLastRefreshDatetime] = useState<string>();
  const chartData = useMemo(() => {
    const result = [];
    (data || []).forEach(it => {
      result.push({
        recordDate: it.recordDate,
        type: '稼动率',
        value: it.utilization
      });
    });
    return result;
  }, [data]);

  function fetchUtilizationHistory() {
    setLoadingHistory(true);
    instance
      .post('/api/utilization/record/list', {
        query: {
          deviceId: props.id,
          recordDateStart: moment().add(-7, 'day').format('YYYY-MM-DD'),
          recordDateEnd: moment().format('YYYY-MM-DD')
        },
        sort: [
          {
            property: 'recordDate',
            direction: 'asc'
          }
        ]
      })
      .then((res) => {
        if (res.data.code === 200) {
          setData(res.data.data);
        }
      })
      .finally(() => {
        setLoadingHistory(false);
      });
  }

  function fetchUtilizationRealtime() {
    setLastRefreshDatetime(moment().format('YYYY-MM-DD HH:mm:ss'));
    setLoadingRealtime(true);
    instance
      .post('/api/utilization/record/realtime', { deviceId: props.id, recordDate: moment().format('YYYY-MM-DD') })
      .then((res) => {
        if (res.data.code === 200) {
          setCurrent(res.data.data);
        }
      })
      .finally(() => {
        setLoadingRealtime(false);
      });
  }

  useEffect(() => {
    if (!!props.id) {
      fetchUtilizationHistory();
      fetchUtilizationRealtime();
    }
  }, [props.id]);

  return (
    <Space style={{ width: '100%' }} direction={'vertical'}>
      <Card>
        <Row>
          <Col span={24}>
            {!!loadingRealtime ? (
              <Skeleton animation />
            ) : (
              (data || []).length === 0 ? (
                <Empty />
              ) : (
                <>
                  <Row justify={'space-between'} align={'center'} style={{ marginBottom: '0.5rem' }}>
                    <Typography.Title heading={6}>
                      {t['title.utilization.realtime']}
                    </Typography.Title>
                    <Row align={'center'} justify={'end'}
                         style={{ color: 'grey', fontSize: '0.8rem', textAlign: 'right' }}>
                      <Col span={24}>
                        {t['label.last_refresh_datetime']}
                      </Col>
                      <Col span={24}>
                        {lastRefreshDatetime}
                      </Col>
                    </Row>
                  </Row>
                  <Row justify={'space-around'} align={'center'}>
                    <Statistic value={current.utilization} countUp precision={2} title={t['title.utilization']} />
                  </Row>
                </>
              )
            )}
          </Col>
        </Row>
      </Card>
      <Card>
        <Row>
          <Col span={24}>
            {!!loadingHistory ? (
              <Skeleton animation />
            ) : (
              (data || []).length === 0 ? (
                <Empty />
              ) : (
                <>
                  <Typography.Title heading={6}>
                    {t['title.utilization.history']}
                  </Typography.Title>
                  <Row>
                    <Col span={24}>
                      <Chart padding={[10, 20, 20, 20]} autoFit height={300} data={chartData}>
                        <Legend visible={false} />
                        <LineAdvance area shape="smooth" position="recordDate*value" color={'type'}></LineAdvance>
                      </Chart>
                    </Col>
                  </Row>
                </>
              )
            )}
          </Col>
        </Row>
      </Card>
    </Space>
  );
};

export default UtilizationPanel;